package app

import (
	"fmt"
	"log"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/cio"
	"github.com/urfave/cli/v2"
)

var DefaultDetachKeys = "ctrl-p,ctrl-q"

var StartCommand = &cli.Command{
	Name:      "start",
	Usage:     "start one or more container",
	ArgsUsage: " CONTAINER [CONTAINER, ...]",
	Flags:     []cli.Flag{},
	Action: func(context *cli.Context) error {
		client, ctx, cancel, err := NewClient(context)
		if err != nil {
			return err
		}
		defer cancel()

		if context.NArg() == 0 {
			return fmt.Errorf("must specify at least one container to start")
		}

		for _, id := range context.Args().Slice() {
			container, err := client.LoadContainer(ctx, id)
			if err != nil {
				log.Fatal(err)
				continue
			}

			opts := []containerd.NewTaskOpts{}
			ioOpts := []cio.Opt{cio.WithFIFODir(context.String("fifo-dir"))}
			task, err := NewTask(ctx, client, container, false, ioOpts, opts...)
			if err != nil {
				log.Fatal(err)
				continue
			}
			if err := task.Start(ctx); err != nil {
				log.Fatal(err)
				continue
			}
			log.Println(id)
		}

		return nil
	},
}
